package com.unlcn.ils.wms.web.controller.borrow;

import cn.huiyunche.commons.domain.ResultDTO;
import cn.huiyunche.commons.exception.BusinessException;
import cn.jiguang.common.utils.StringUtils;
import com.unlcn.ils.wms.backend.service.borrow.WmsBorrowCarService;
import com.unlcn.ils.wms.backend.service.borrow.WmsReturnCarService;
import com.unlcn.ils.wms.base.dto.BorrowDetailDTO;
import com.unlcn.ils.wms.base.dto.ReturnCarLineDTO;
import com.unlcn.ils.wms.base.dto.ReturnDetailDTO;
import com.unlcn.ils.wms.base.model.stock.WmsBorrowCar;
import com.unlcn.ils.wms.base.model.stock.WmsBorrowCarDetail;
import com.unlcn.ils.wms.base.model.stock.WmsReturnCar;
import com.unlcn.ils.wms.web.vo.borrow.WmsBorrowCarVo;
import com.unlcn.ils.wms.web.vo.borrow.WmsReturnCarVo;
import jodd.util.StringUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Array;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by lenovo on 2017/10/20.
 */
@RestController
@RequestMapping("/return")
public class WmsReturnCarController {

    private Logger LOGGER = LoggerFactory.getLogger(WmsReturnCarController.class);

    @Autowired
    private WmsReturnCarService wmsReturnCarService;

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
    }

    /**
     * 还车登记列表
     * @param wmsReturnCarVo
     * @return
     */
    @RequestMapping(value = "/returnLine", method = RequestMethod.POST)
    public ResultDTO<Object> borrowLine(@RequestBody WmsReturnCarVo wmsReturnCarVo) {
        LOGGER.info("WmsReturnCarController.returnLine param: {}" + wmsReturnCarVo.toString());
        ResultDTO resultDTO = null;

        try {
            Map<String, Object> paramsMap = new HashMap<String, Object>();
            paramsMap.put("limitStart", wmsReturnCarVo.getStartIndex());
            paramsMap.put("limitEnd", wmsReturnCarVo.getPageSize());
            paramsMap.put("deleteFlag", 1);
            paramsMap.put("orderByClause", " wrc.gmt_create desc ");

            // 还车姓名
            if (!StringUtil.isEmpty(wmsReturnCarVo.getRcReturnName())) {
                paramsMap.put("rcReturnName", wmsReturnCarVo.getRcReturnName());
            }
            // 还车人部门
            if (!StringUtil.isEmpty(wmsReturnCarVo.getRcReturnDepartment())) {
                paramsMap.put("rcReturnDepartment", wmsReturnCarVo.getRcReturnDepartment());
            }
            // 还车起始时间
            if (wmsReturnCarVo.getReturnStartTime() != null) {
                paramsMap.put("returnStartTime", wmsReturnCarVo.getReturnStartTime());
            }
            // 还车截止时间
            if (wmsReturnCarVo.getReturnEndTime() != null) {
                paramsMap.put("returnEndTime", wmsReturnCarVo.getReturnEndTime());
            }
            // 所属部门
            if (!StringUtil.isEmpty(wmsReturnCarVo.getRcWhcode())) {
                paramsMap.put("rcWhcode", wmsReturnCarVo.getRcWhcode());
            }

            // 查询还车登记数据
            List<ReturnCarLineDTO> wmsBorrowCarList = wmsReturnCarService.returnLine(paramsMap);
            // 借用登记数据统计
            Integer count = wmsReturnCarService.returnLineCount(paramsMap);

            wmsReturnCarVo.setTotalRecord(count);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("totalRecord", wmsReturnCarVo.getTotalRecord());
            map.put("totalPage", wmsReturnCarVo.getTotalPage());
            map.put("pageNo", wmsReturnCarVo.getPageNo());
            map.put("pageSize", wmsReturnCarVo.getPageSize());
            map.put("wmsBorrowCarList", wmsBorrowCarList);

            resultDTO = new ResultDTO<Object>(true, map, "成功添加运单信息");
        } catch (BusinessException e) {
            LOGGER.error("WmsReturnCarController.returnLine businessException: {}", e);
            resultDTO = new ResultDTO(false, e.getMessage());
        } catch (Exception e) {
            LOGGER.error("WmsReturnCarController.returnLine error: {}", "系统异常...");
            resultDTO = new ResultDTO(false, "系统异常...");
        }

        return resultDTO;
    }

    /**
     * 查询还车单明细
     * @param returnId
     * @return
     */
    @RequestMapping(value = "/findReturnDetail/{returnId}", method = RequestMethod.GET)
    public ResultDTO<Object> findReturnDetail(@PathVariable  String returnId) {
        LOGGER.info("WmsReturnCarController.findReturnDetail param: {}" + returnId);
        ResultDTO resultDTO = null;

        try {
            List<WmsBorrowCarDetail> wmsBorrowCarDetailList = wmsReturnCarService.findReturnDetail(Long.valueOf(returnId));
            resultDTO = new ResultDTO<Object>(true, wmsBorrowCarDetailList, "成功添加运单信息");
        } catch (BusinessException e) {
            LOGGER.error("WmsReturnCarController.findReturnDetail businessException: {}", e);
            resultDTO = new ResultDTO(false, e.getMessage());
        } catch (Exception e) {
            LOGGER.error("WmsReturnCarController.findReturnDetail error: {}", "系统异常...");
            resultDTO = new ResultDTO(false, "系统异常...");
        }

        return resultDTO;
    }

    /**
     * 新增还车单
     * @param wmsReturnCarVo
     * @return
     */
    @RequestMapping(value="/add")
    public ResultDTO add(@RequestBody  WmsReturnCarVo wmsReturnCarVo) {
        LOGGER.info("WmsReturnCarController.add param: {}" + wmsReturnCarVo);
        ResultDTO<Object> resultDTO = null;

        try {
            if (StringUtil.isEmpty(wmsReturnCarVo.getRcBorrowNo())
                    && CollectionUtils.isEmpty(wmsReturnCarVo.getWmsBorrowCarDetailList()))
                throw new BusinessException("借车单号和车架号必须填一项!");

            WmsReturnCar wmsReturnCar = new WmsReturnCar();
            BeanUtils.copyProperties(wmsReturnCarVo, wmsReturnCar);
            wmsReturnCarService.add(wmsReturnCar, wmsReturnCarVo.getWmsBorrowCarDetailList());
            resultDTO = new ResultDTO<Object>(true, "成功新增!");
        } catch (BusinessException e) {
            LOGGER.error("WmsReturnCarController.add businessException: {}", e);
            resultDTO = new ResultDTO(false, e.getMessage());
        } catch (Exception e) {
            LOGGER.error("WmsReturnCarController.add error: {}", e);
            resultDTO = new ResultDTO(false, "系统异常...");
        }

        return resultDTO;
    }

    /**
     * 查询还车单明细
     * @param rcId
     * @return
     */
    @RequestMapping(value = "/queryModifyDetail/{rcId}", method = RequestMethod.GET)
    public ResultDTO<Object> queryModifyDetail(@PathVariable  Long rcId) {
        LOGGER.info("WmsReturnCarController.add param: {}" + rcId);
        ResultDTO resultDTO = null;

        try {
            List<ReturnDetailDTO> returnDetailDTOList = wmsReturnCarService.queryModifyDetail(rcId);
            resultDTO = new ResultDTO<Object>(true, returnDetailDTOList, "成功添加运单信息");
        } catch (BusinessException e) {
            LOGGER.error("WmsReturnCarController.queryModifyDetail businessException: {}", e);
            resultDTO = new ResultDTO(false, e.getMessage());
        } catch (Exception e) {
            LOGGER.error("WmsReturnCarController.queryModifyDetail error: {}", e);
            resultDTO = new ResultDTO(false, "系统异常...");
        }

        return resultDTO;
    }

    /**
     * 编辑还车单
     * @param wmsReturnCarVo
     * @return
     */
    @RequestMapping(value = "/modify", method = RequestMethod.POST)
    public ResultDTO modify(@RequestBody WmsReturnCarVo wmsReturnCarVo) {
        LOGGER.info("WmsReturnCarController.modify param: {}" + wmsReturnCarVo.toString());
        ResultDTO<Object> resultDTO = null;

        try {
            if (wmsReturnCarVo.getRcId() == null)
                throw new BusinessException("id不能为空!");
            if (CollectionUtils.isEmpty(wmsReturnCarVo.getWmsBorrowCarDetailList()))
                throw new BusinessException("车辆信息不能为空!");

            WmsReturnCar  wmsReturnCar = new WmsReturnCar();
            BeanUtils.copyProperties(wmsReturnCarVo, wmsReturnCar);
            wmsReturnCarService.modify(wmsReturnCar, wmsReturnCarVo.getWmsBorrowCarDetailList());
            resultDTO = new ResultDTO<Object>(true, "成功编辑!");
        } catch (BusinessException e) {
            LOGGER.error("WmsReturnCarController.modify businessException: {}", e);
            resultDTO = new ResultDTO(false, e.getMessage());
        } catch (Exception e) {
            LOGGER.error("WmsReturnCarController.modify error: {}", "系统异常...");
            resultDTO = new ResultDTO(false, "系统异常...");
        }

        return resultDTO;
    }

    /**
     * 删除借车单
     * @param rcId
     * @return
     */
    @RequestMapping(value="/del")
    public ResultDTO del(@RequestBody Long[] rcId) {
        LOGGER.info("WmsReturnCarController.del param: {}" + rcId);
        ResultDTO<Object> resultDTO = null;

        try {
            if (rcId == null)
                throw new BusinessException("id不能为空!");

            wmsReturnCarService.delete(Arrays.asList(rcId));
            resultDTO = new ResultDTO<Object>(true, "成功删除!");
        } catch (BusinessException e) {
            LOGGER.error("WmsReturnCarController.del businessException: {}", e);
            resultDTO = new ResultDTO(false, e.getMessage());
        } catch (Exception e) {
            LOGGER.error("WmsReturnCarController.del error: {}", e);
            resultDTO = new ResultDTO(false, "系统异常...");
        }

        return resultDTO;
    }

    /**
     * 获取借车单的车辆信息
     * @param borrowNo
     * @return
     */
    @RequestMapping(value="/getDetail/{borrowNo}")
    public ResultDTO findDetail(@PathVariable String borrowNo) {
        LOGGER.info("WmsReturnCarController.getDetail param: {}" + borrowNo);
        ResultDTO<Object> resultDTO = null;

        try {
            if (borrowNo == null)
                throw new BusinessException("借车单号不能为空!");

            resultDTO = new ResultDTO<Object>(true, wmsReturnCarService.getDetail(borrowNo), "成功获取借车单详情!");
        } catch (BusinessException e) {
            LOGGER.error("WmsReturnCarController.getDetail businessException: {}", e);
            resultDTO = new ResultDTO(false, e.getMessage());
        } catch (Exception e) {
            LOGGER.error("WmsReturnCarController.getDetail error: {}", e);
            resultDTO = new ResultDTO(false, "系统异常...");
        }

        return resultDTO;
    }
}
